<template>
  <div class="issue_box">
    <div class="map_title">
      <div class="back_box">
        <img
          @click="back"
          src="../assets/img/返回.png"
          alt="返回按钮"
          style="margin-right: 5px; border-right: 1px solid #929292"
        />
        <img
          @click="jump('/home')"
          src="../assets/img/homes (1).png"
          alt="主页按钮"
        />
      </div>
      <p>发布攻略</p>
    </div>

    <!-- 标题发布 -->
    <div class="issue_title">
      <input 
        v-model="form.title" 
        type="text" 
        placeholder="好的标题能够吸引更多的用户哦～"
      >
      <p class="error-message" v-if="errors.title">{{ errors.title }}</p>
    </div>

    <!-- 图片封面上传 -->
    <div class="issue_imgFile">
      <div>
        <van-uploader 
          :after-read="handleMainImagesUpload" 
          style="margin-left: 20px;" 
          v-model="fileList" 
          multiple 
        />
        <p class="error-message" v-if="errors.mainImages">{{ errors.mainImages }}</p>
      </div>
      <div style="margin-top: 5px;">
        <van-uploader 
          :after-read="handleCoverUpload" 
          style="margin-left: 20px;" 
          v-model="fileItem" 
          multiple
          :max-count="1" 
        />
        <p class="error-message" v-if="errors.cover">{{ errors.cover }}</p>
      </div>
    </div>

    <!-- 内容发布 -->
    <div class="issue_content">
      <textarea
        v-model="form.content"
        name=""
        cols="30"
        rows="10"
        placeholder="文字越多,越受欢迎"
      ></textarea>
      <p class="error-message" v-if="errors.content">{{ errors.content }}</p>
    </div>

    <!-- 选择类型 -->
    <div class="issue_type">
      <p>请选择类型：</p>
      <div class="types">
        <input 
          type="radio" 
          v-model="form.type" 
          :value="1" 
          name="type" 
          id="guide" 
        />
        <label for="guide">攻略</label>
      </div>
      <div class="types">
        <input 
          type="radio" 
          v-model="form.type" 
          :value="2" 
          name="type" 
          id="intro" 
        />
        <label for="intro">游记</label>
      </div>
      <div class="types">
        <input 
          type="radio" 
          v-model="form.type" 
          :value="3" 
          name="type" 
          id="ask" 
        />
        <label for="ask">问答</label>
      </div>
      <!-- <p class="error-message" v-if="errors.type">{{ errors.type }}</p> -->
    </div>

    <div class="scenic_area">
      <p>请选择景区：</p>
      <div style="display:flex;flex-wrap: wrap;">
        <div class="scenic_area_types" v-for="(item, index) in scenicData" :key="item.id">
          <div class="scenic_types">
            <label :for="item.id">
              <img :src="'https://jingqu.kuxia.top' + item.img" alt="景区图片">
            </label>
            <div class="scenic_name">
              {{ item.name }}
            </div>
            <input 
              type="radio" 
              v-model="form.scenicId" 
              :value="item.id" 
              :id="item.id" 
              style="position: absolute;" 
              name="scenics"
            >
          </div>
        </div>
      </div>
      <p class="error-message" v-if="errors.scenicId">{{ errors.scenicId }}</p>
    </div>

    <!-- 发布按钮 -->
    <div 
      class="issue_btn"
      @click="submitForm"
      :class="{ 'disabled': isSubmitting }"
      :disabled="isSubmitting"
    >
      {{ isSubmitting ? '发布中...' : '发布' }}
    </div>
  </div>
</template>

<script setup>
import { useRouter } from "vue-router";
import { ref, reactive, onMounted } from "vue";
import { uploadFile, sccenic } from '../api/issue';
import { introAdd, askAdd, traveAdd } from '../api/issue';
import { showToast } from 'vant';

const router = useRouter();
const userId = 158; // 用户ID

// 表单数据
const form = reactive({
  title: '',
  content: '',
  type: null,
  scenicId: null,
  cover: '',
  mainImages: []
});

// 错误信息
const errors = reactive({
  title: '',
  content: '',
  type: '',
  scenicId: '',
  cover: '',
  mainImages: ''
});

// 状态管理
const isSubmitting = ref(false);
const fileList = ref([]); // 主图文件列表
const fileItem = ref([]); // 封面文件列表
const scenicData = ref([]); // 景区数据

// 生命周期钩子
onMounted(() => {
  fetchScenicData();
});

// 获取景区数据
const fetchScenicData = async () => {
  try {
    const res = await sccenic();
    scenicData.value = res.data;
  } catch (error) {
    console.error('获取景区数据失败', error);
    showToast({
      message: '获取景区数据失败，请稍后重试',
      position: 'top'
    });
  }
};

// 处理主图上传
const handleMainImagesUpload = async (file) => {
  try {
    if (!file || !file.file) {
      throw new Error('未选择文件');
    }
    console.log(file);
    
    const formData = new FormData();
    formData.append('file', file.file);
    console.log(formData);
    
    // 统一使用 async/await 处理请求
    // 将userId放在headers中
    const res = await uploadFile(formData, userId);    
    

    if (res.code !== 1) {
      throw new Error(res.msg || '上传失败');
    }
    
    // 假设服务器返回图片URL
    form.mainImages.push(res.data.url);
    showToast({
      message: '图片上传成功',
      position: 'top'
    });
  } catch (error) {
    console.error('图片上传失败', error);
    errors.mainImages = '图片上传失败，请重试';
    showToast({
      message: error.message || '图片上传失败',
      position: 'top'
    });
  }
}

// 处理封面上传
const handleCoverUpload = async (file) => {
  try {
    if (!file || !file.file) {
      throw new Error('未选择文件');
    }
    
    const formData = new FormData();
    formData.append('file', file.file);
    
    // 将userId放在headers中
    const res = await uploadFile(formData, userId);    
    if (res.code !== 1) {
      throw new Error(res.msg || '上传失败');
    }
    
    form.cover = res.data.url;
    showToast({
      message: '封面上传成功',
      position: 'top'
    });
  } catch (error) {
    console.error('封面上传失败', error);
    errors.cover = '封面上传失败，请重试';
    showToast({
      message: error.message || '封面上传失败',
      position: 'top'
    });
  }
};

// 表单验证
const validateForm = () => {
  // 重置错误信息
  Object.keys(errors).forEach(key => {
    errors[key] = '';
  });
  
  let isValid = true;
  
  // 验证标题
  if (!form.title.trim()) {
    errors.title = '请输入标题';
    isValid = false;
  }
  
  // 验证内容
  if (!form.content.trim()) {
    errors.content = '请输入内容';
    isValid = false;
  }
  
  // 验证类型
  if (!form.type) {
    errors.type = '请选择内容类型';
    isValid = false;
  }
  
  // 验证景区
  if (!form.scenicId) {
    errors.scenicId = '请选择景区';
    isValid = false;
  }
  
  // 验证封面和轮播图
  if (form.type === 1 || form.type === 2) { // 攻略或游记需要封面和轮播图
    if (!form.cover) {
      errors.cover = '请上传封面图';
      isValid = false;
    }
    
    if (!form.mainImages || form.mainImages.length === 0) {
      errors.mainImages = '请上传轮播图';
      isValid = false;
    }
  } else if (form.type === 3) { // 问答不需要封面
    if (!form.cover) {
      errors.cover = '请上传封面图';
      isValid = false;
    }
  }
  
  return isValid;
};

// 提交表单
const submitForm = async () => {
  if (isSubmitting.value) return;
  
  if (!validateForm()) return;
  
  isSubmitting.value = true;
  
  try {
    let response;

    console.log(form);
    console.log(form.content);
    
    
    
    // 根据类型选择不同的API
    if (form.type === 1) {
      // 攻略
      response = await introAdd({
        title: form.title,
        introduce: form.content,
        scenic_id: form.scenicId,
        bannar: form.mainImages.join(','),
        img: form.cover,
        user_id:userId,
        like_num:6,
        collect_num:3,
      },userId);
    console.log(response);

    } else if (form.type === 2) {
      // 游记
      response = await traveAdd({
        title: form.title,
        content: form.content,
        banner: form.mainImages.join(','),
        cover: form.cover,
        user_id: userId,
      },userId);
    } else if (form.type === 3) {
      // 问答
      response = await askAdd({
        content: form.content,
        user_id: userId,
        pid: 0,
      },userId);
    }
    
    if (response.code === 1) {
      showToast({
        message: '发布成功',
        position: 'top'
      });
      
      // 发布成功后跳转到成功页面或刷新当前页面
      router.push({ name: '发布成功' });
    } else {
      showToast({
        message: response.msg || '发布成功',
        position: 'top'
      });
    }
  } catch (error) {
    console.error('发布失败', error);
    showToast({
      message: '发布成功',
      position: 'top'
    });
  } finally {
    isSubmitting.value = false;
  }
};

// 导航方法
const jump = (url) => {
  router.push(url);
};

const back = () => {
  router.back();
};
</script>

<style scoped>
/* 保持原有样式不变 */
/* 标题顶部导航栏 */
.map_title {
  width: 100%;
  height: 60px;
  display: flex;
  align-items: center;
  background: #fff;
  height: 40px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  border-bottom: #929292 1px solid;
}

.map_title > p {
  margin-left: 25%;
}

/* 返回按键 */
.back_box {
  width: 15%;
  height: 50%;
  border: 1px solid #929292;
  border-radius: 50px;
  display: flex;
  align-items: center;
  padding: 1%;
  margin-left: 4%;
}

.back_box > img {
  width: 25px;
  height: 20px;
}

/* 标题发布 */
.issue_title {
  width: 100%;
  margin-top: 42px;
  background: #fff;
  padding-top: 2%;

  > input {
    width: 90%;
    padding: 1%;
    padding-bottom: 2%;
    margin-left: 4%;
    border: none;
    font-size: 14px;
    border-bottom: #929292 1px solid;
  }
}

/* 文件图片上传 */
.issue_imgFile {
  width: 100%;
  /* height: 100px; */
  background-color: #fff;
}

/* 描述发布 */
.issue_content {
  width: 100%;
  height: 140px;
  background-color: #fff;
  border-bottom: #929292 1px solid;
  > textarea {
    width: 90%;
    height: 100%;
    margin-left: 4%;
    border: none;
  }
}

/* 发布类型选择 */

.issue_type {
  width: 90%;
  padding-top: 6%;
  padding-left: 5%;
  padding-right: 5%;
  height: 40px;
  background-color: #fff;
  display: flex;
  font-size: 15px;
  color: #505050;
}
.types {
  margin-left: 5%;
  > input {
    margin-right: 4px;
  }
}

/* 选择景区 */
.scenic_area{
   width: 90%;
  padding-left: 5%;
  padding-right: 5%;
  padding-bottom:13%;
  background-color: #fff;
  font-size: 15px;
  color: #505050;
}
.scenic_types{
  width: 90px;
  height: 90px;
  margin-top: 2%;
  margin-left: 5%;
  overflow: hidden;
  position: relative;
   img{
    width: 90px;
    height: 90px;
  }
  input{
    position: absolute;
    top: 0;
    right: 0;
  }
}

/* 景区名字 */
.scenic_name{
  width: 90px;
  height: 20px;
  background-color: rgba(0, 0, 0, 0.4);
  position: absolute;
  bottom: 0;
  color: #fff;
  font-size: 13px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: flex;
  justify-content: center;
  align-items: center;
}

.scenic_area_types{
  margin-left:5%;
  margin-top:3%;
}

/* 发布 */
.issue_btn{
  width: 90%;
  height: 40px;
  bottom: 1%;
  left: 5%;
  font-size: 15px;
  border-radius: 8px;
  display: flex;
  position: fixed;
  background-color: #5BA0EA;
  justify-content: center;
  align-items: center;
  color: #fff;
}


.issue_box{
  height:90vh;
  background-color: #fff;
}

/* 添加错误提示样式 */
.error-message {
  color: #f56c6c;
  font-size: 12px;
  padding-left: 20px;
  padding-top: 5px;
}

/* 禁用状态样式 */
.issue_btn.disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}
</style>    